package com.wolfking.jeesite.config;

import com.google.common.collect.ImmutableMap;
import com.wolfking.jeesite.exception.SignException;
import com.wolfking.jeesite.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Map;

import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;

@Slf4j
@SuppressWarnings("all")
@ControllerAdvice(basePackages = {"com.wolfking.jeesite"})
public class SignExceptionHandler {

    @Autowired
    private SsoConfig ssoConfig;

    @ExceptionHandler({SignException.class})
    public Object signException(SignException e) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String contentType = request.getContentType();
        boolean json = StringUtils.isNotBlank(contentType) &&
                contentType.toLowerCase(Locale.ROOT).contains("application/json");
        if (StringUtils.isEmpty(e.getPermission())) {
            if (!json) {
                String loginFromUrl = ssoConfig.getSelfRootUrlByRequest() + "/login";
                String requestUrl = RequestUtil.getRequestUrlEncode(request, "ticket");
                requestUrl = "from=" + requestUrl;
                loginFromUrl += "?";
                loginFromUrl += requestUrl;
                return new ModelAndView("redirect:" + loginFromUrl);
            } else {
                Map<String, String> map = ImmutableMap.of("detail", "用户未登录", "message", "用户未登录");
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(APPLICATION_JSON_UTF8);
                return new ResponseEntity<>(map, headers, HttpStatus.OK);
            }
        } else {
            if (!json) {
                ModelAndView model = new ModelAndView("error/exception");
                if (StringUtils.isNotBlank(ssoConfig.getPermissionUrl())) {
                    model.setViewName("redirect:" + ssoConfig.getPermissionUrl());
                }
                model.addObject("message", e.getPermission());
                model.addObject("detail", StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : "用户权限不足，请联系管理员");
                return model;
            } else {
                Map<String, String> map = ImmutableMap.of("detail", "用户权限不足，请联系管理员", "message", e.getPermission());
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(APPLICATION_JSON_UTF8);
                return new ResponseEntity<>(map, headers, HttpStatus.OK);
            }
        }
    }
}
